package com.runvp.netty.runnables;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.config.RunvpConfig;
import com.runvp.common.enums.*;
import com.runvp.common.model.tcp.MessageReceiveBody;
import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.common.utils.DateUtils;
import com.runvp.netty.constant.NettyConstant;
import com.runvp.service.biz.domain.BizDevice;
import com.runvp.service.build.BuildQRCode;
import com.runvp.service.tcp.TcpService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
public class DeviceReportBaseIfoRunnable implements Runnable {

    private Channel channel;

    private TcpService tcpService;

    private MessageReceiveBody parseBody;

    public DeviceReportBaseIfoRunnable(Channel channel, TcpService tcpService, MessageReceiveBody parseBody) {
        this.channel = channel;
        this.tcpService = tcpService;
        this.parseBody = parseBody;
    }

    @Override
    public void run() {
        handle(channel);
    }


    /**
     * 设备发送收费方案包
     */
    public void handle(Channel channel) {
        long st = System.currentTimeMillis();
        long ast = st;
        String sn = "";
        try{
            String batchNo = System.nanoTime()+"";
            String json = JSONObject.toJSONString(parseBody);
            sn = NettyConstant.allOnlineChannleIds.get(NettyConstant.getChannelId(channel));
            log.info("设备上报基本信息报文实体 ：{}", json);
        }catch (Exception e){
            log.error("本次设备上报基本信息【{}】处理异常共耗时:【{} ms】,error:{}",sn,(System.currentTimeMillis()-ast),e.getMessage());
        }finally {
            log.info("本次设备上报基本信息【{}】线程池内解析处理共耗时:【{} ms】",sn,(System.currentTimeMillis()-ast));
        }
    }

    /**
     * 初始化默认数据
     *
     * @return str
     */
    private void createBizDevice(MessageReceiveBody parseBody) {
        String sn = parseBody.getTerminalId();
        BizDevice query = new BizDevice();
        query.setDeviceCode(sn);
        List<BizDevice> deviceList = tcpService.instanceIBizDeviceService().selectBizDeviceList(query);
        BizDevice device;
        if (CollectionUtils.isEmpty(deviceList)) {
            device = new BizDevice();
            device.setDeviceType(DeviceType.WECHAT.getCode());
            device.setStatus(EnableStatus.DISABLE.getCode());
            device.setStockStatus(YesOrNo.YES.getCode());
            device.setDoorLockStatus(DoorLockStatus.CLOSE.getCode());
            device.setRenewStatus(RenewStatus.NORMAL.getCode());
            device.setDueDtime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, "2100-12-29 23:59:59"));
            device.setCreateTime(DateUtils.getNowDate());
            device.setDeviceCode(sn);
        } else {
            device = deviceList.get(0);
        }
        device.setLastUpdateTime(DateUtils.getNowDate());
        device.setLineStatus(LineStatus.ON_LINE.getCode());
        if (device.getId() == null) {
            tcpService.instanceIBizDeviceService().insertBizDevice(device);
            log.info("设备【{}】执行新增,执行时间:【{}】", sn, DateUtils.now());
        } else {
            device.setUpdateTime(DateUtils.getNowDate());
            device.setQrCode(BuildQRCode.createCode(device.getDeviceCode(), RunvpConfig.getPreview() + "/wechat.html?baseSn=" + device.getDeviceCode()));
            tcpService.instanceIBizDeviceService().updateBizDevice(device);
            log.info("设备【{}】执行修改,执行时间:【{}】", sn, DateUtils.now());
        }
    }

    /**
     * 结构结果体
     * @return str
     */
    private JSONObject buildBody(){
        StringBuilder sb = new StringBuilder();
        JSONObject map = new JSONObject();
        map.put("id","1");
        return map;
    }


    /**
     * 默认报文
     *
     * @return MessageResBody
     */
    public MessageResBody defaultRes() {
        MessageResBody resBody = new MessageResBody(NettyType.SERVER_RECEIVE_DEVICE.getCode(), NettyCmd.SERVER_RES_BASE_INFO.getCode());
        resBody.setDid("000000000000");
        resBody.setVersion("01");
        resBody.setBodyJson(buildBody()).buildRes();
        log.info("服务器组装回应设备上报基本信息报文完毕");
        return resBody;
    }

}
